package com.maxuxu.scihome.interceptor;

import com.maxuxu.scihome.pojo.User;
import com.maxuxu.scihome.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @className: UserRealm
 * @author: Maxuxu
 * @date: 2022/7/7 15:34
 * @description: shiro的权限验证
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    User user;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 这样写每个人都会进行授权，但这是不合理的。应当把授权信息写进数据库，所有看下面的语句
//        info.addStringPermission("user:add");

        // 获取当前登陆的对象
        Subject subject = SecurityUtils.getSubject();
        // 获取user对象
        User currentuser = (User) subject.getPrincipal();
        // 从数据库中获取权限
        info.addStringPermission(currentuser.getPerms());
        System.out.println(subject.isAuthenticated());
        // System.out.println(subject.isPermitted("user:admin"));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("实现了认证");
        UsernamePasswordToken usertoken = (UsernamePasswordToken) authenticationToken;

        // String name = "maxuxu2000";
        // String password = "123456";
        // 获取完整的用户信息
        user.setLoginname(usertoken.getUsername());

        User userByAny = userService.selectUserByAny(user);
        if (userByAny == null){
            return null;
        }
        // 生成随机的盐值
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // 设置加密的次数
        int times = 2;
        // 选择加密算法，此处使用md5加密
        String alorithm = "md5";
        String encodepassword = new SimpleHash(alorithm, userByAny.getPassword(), salt, times).toString();
        System.out.printf("原始密码是 %s , 盐是： %s, 运算次数是： %d, 运算出来的密文是：%s", userByAny.getPassword(), salt, times, encodepassword);

        /*
        第一个参数时用户属性
        第二个属性是密码
        第三个属性是当前的对象。
         */
        return new SimpleAuthenticationInfo(userByAny, userByAny.getPassword(), "");
    }
}
